package com.kaiwukj.android.ufamily.mvp.ui.page.service.gm.playback;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.app.NotificationCompat;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ScreenUtils;
import com.kaiwukj.android.mcas.utils.UToast;
import com.kaiwukj.android.ufamily.R;
import com.kaiwukj.android.ufamily.app.MyApplication;
import com.kaiwukj.android.ufamily.app.base.review.BaseActivity;
import com.kaiwukj.android.ufamily.app.constant.ARouterUrlKt;
import com.kaiwukj.android.ufamily.app.constant.ReceiverKeys;
import com.kaiwukj.android.ufamily.mvp.http.entity.helper.GMDeviceInfo;
import com.qmuiteam.qmui.widget.QMUISlider;
import com.videogo.errorlayer.ErrorInfo;
import com.videogo.exception.ErrorCode;
import com.videogo.exception.InnerException;
import com.videogo.openapi.EZConstants;
import com.videogo.openapi.EZOpenSDK;
import com.videogo.openapi.EZOpenSDKListener;
import com.videogo.openapi.EZPlayer;
import com.videogo.openapi.bean.EZDeviceRecordFile;
import com.videogo.stream.EZDeviceStreamDownload;

import java.io.File;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;

@Route(path = ARouterUrlKt.GMVideoPlayBack)
public class GMOrderVideoPlayBackActivity extends BaseActivity {

    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.view_video)
    SurfaceView surfaceView;
    @BindView(R.id.container_loading)
    ViewGroup containerLoading;
    @BindView(R.id.slider)
    QMUISlider slider;
    @BindView(R.id.tv_time_current)
    TextView tvCurrentTime;
    @BindView(R.id.tv_time_total)
    TextView tvTotalTime;
    @BindView(R.id.iv_pause)
    ImageView ivPause;
    @BindView(R.id.iv_voice)
    ImageView ivVoice;
    @BindView(R.id.container_header)
    ViewGroup containerHeader;
    @BindView(R.id.container_bottom)
    ViewGroup containerBottom;

    private SurfaceHolder mRealHolder;

    @Autowired
    GMDeviceInfo deviceInfo;
    @Autowired
    EZDeviceRecordFile playbackFile;

    // 播放状态
    private int status = RemoteListContant.STATUS_INIT;

    private EZPlayer mPlaybackPlayer = null;
    private boolean isSoundEnable = true;


    // 录像时间
    private int mRecordSecond = 0;

    private boolean isReplay = false;

    // 控制栏时间值
    private int mControlDisplaySec = 0;
    // 定时器
    private Timer mUpdateTimer = null;
    // 定时器执行的任务
    private TimerTask mUpdateTimerTask = null;

    @OnClick(R.id.container_left)
    void onBackClick() {
        onBackPressedSupport();
    }

    @OnClick(R.id.container_pause)
    void onPauseOrPlayClick() {
        playOrPause();
    }

    @OnClick(R.id.container_sound)
    void onSoundClick() {
        if (mPlaybackPlayer == null) return;
        if (isSoundEnable) {
            ivVoice.setImageResource(R.mipmap.ic_gm_video_sound_close);
            mPlaybackPlayer.closeSound();
            isSoundEnable = false;
        } else {
            ivVoice.setImageResource(R.mipmap.ic_gm_video_sound_open);
            mPlaybackPlayer.openSound();
            isSoundEnable = true;
        }
    }


    @Override
    protected int getLayoutId() {
        ARouter.getInstance().inject(this);
        ScreenUtils.setFullScreen(this);
        return R.layout.activity_gm_playback;
    }

    @Override
    public boolean useLandscape() {
        return true;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        tvTitle.setText("视频回放");
        mRealHolder = surfaceView.getHolder();
       /* surfaceView.setOnClickListener(v->{
            showDisposable = Observable.timer(3000,)
        });*/
        initEZPlayer();

        int diffMs = (int) (playbackFile.getStopTime().getTimeInMillis() - playbackFile.getStartTime().getTimeInMillis());
        String totalTime = RemoteListUtil.convToUIDuration(diffMs / 1000);
        tvTotalTime.setText(totalTime);
        tvCurrentTime.setText("00:00:00");
        slider.setTickCount(RemoteListContant.PROGRESS_MAX_VALUE);

        slider.setCallback(new QMUISlider.Callback() {
            @Override
            public void onProgressChange(QMUISlider slider, int progress, int tickCount, boolean fromUser) {
                if (playbackFile != null) {
                    long time = playbackFile.getStopTime().getTimeInMillis() - playbackFile.getStartTime().getTimeInMillis();
                    int diffSeconds = (int) (time * progress / RemoteListContant.PROGRESS_MAX_VALUE) / 1000;
                    String convToUIDuration = RemoteListUtil.convToUIDuration(diffSeconds);
                    LogUtils.d("convToUIDuration----------------->" + convToUIDuration);
                    tvCurrentTime.setText(convToUIDuration);
                    //beginTimeTV.setText(convToUIDuration);
                }
            }

            @Override
            public void onTouchDown(QMUISlider slider, int progress, int tickCount, boolean hitThumb) {

            }

            @Override
            public void onTouchUp(QMUISlider slider, int progress, int tickCount) {

            }

            @Override
            public void onStartMoving(QMUISlider slider, int progress, int tickCount) {

            }

            @Override
            public void onStopMoving(QMUISlider slider, int progress, int tickCount) {
                if (progress == RemoteListContant.PROGRESS_MAX_VALUE) {
                    stopRemoteListPlayer();
                    handlePlaySegmentOver();
                    return;
                }
                if (playbackFile != null) {
                    long beginTime = playbackFile.getStartTime().getTimeInMillis();
                    long endTime = playbackFile.getStopTime().getTimeInMillis();
                    long avg = (endTime - beginTime) / RemoteListContant.PROGRESS_MAX_VALUE;
                    long trackTime = beginTime + (progress * avg);

                    //seekInit(true, false);
                    // slider.setCurrentProgress(progress);

                    LogUtils.i("onSeekBarStopTracking, begin time:"
                            + beginTime + " endtime:" + endTime
                            + " avg:" + avg + " MAX:"
                            + RemoteListContant.PROGRESS_MAX_VALUE
                            + " tracktime:" + trackTime);
                    if (mPlaybackPlayer != null) {
                        Calendar seekTime = Calendar.getInstance();
                        seekTime.setTime(new Date(trackTime));
                        mPlaybackPlayer.seekPlayback(seekTime);
                    }
                }
            }
        });


    }

    @Override
    protected void initData(Bundle savedInstanceState) {

    }

    @Override
    protected void onResume() {
        super.onResume();
        // 判断是否处理暂停状态
        if (notPause || status == RemoteListContant.STATUS_DECRYPT) {
            surfaceView.setVisibility(View.VISIBLE);
            // onActivityResume();
            startUpdateTimer();
            // isDateSelected = false;
        }
    }

    private void initEZPlayer() {
        containerLoading.setVisibility(View.VISIBLE);
        mPlaybackPlayer = EZOpenSDK.getInstance().createPlayer(deviceInfo.getDeviceSerial(), deviceInfo.getCameraNo());
        mPlaybackPlayer.setPlayVerifyCode(deviceInfo.getVerifyCode());

        mRealHolder.addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceCreated(SurfaceHolder holder) {
                if (mPlaybackPlayer != null) mPlaybackPlayer.setSurfaceHold(holder);
                mRealHolder = holder;
            }

            @Override
            public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
                if (mPlaybackPlayer != null) {
                    mPlaybackPlayer.setSurfaceHold(holder);
                }
                mRealHolder = holder;
            }

            @Override
            public void surfaceDestroyed(SurfaceHolder holder) {
                if (mPlaybackPlayer != null) mPlaybackPlayer.setSurfaceHold(null);
                mRealHolder = null;
            }
        });

        //设置Handler, 该handler将被用于从播放器向handler传递消息
        mPlaybackPlayer.setHandler(playBackHandler);

        //设置播放器的显示Surface
        mPlaybackPlayer.setSurfaceHold(mRealHolder);

        mPlaybackPlayer.startPlayback(playbackFile);

    }

    private void startUpdateTimer() {
        stopUpdateTimer();
        // 开始录像计时
        mUpdateTimer = new Timer();
        mUpdateTimerTask = new TimerTask() {
            @Override
            public void run() {
                // 流量提醒
           /*     if (mLimitFlowDialog != null && mLimitFlowDialog.isShowing() && mCountDown > 0) {
                    mCountDown--;
                }
*/
                // 录像显示
               /* if (isRecording) {
                    // 更新录像时间
                    Calendar OSDTime = null;
                    if (mPlaybackPlayer != null)
                        OSDTime = mPlaybackPlayer.getOSDTime();
                    if (OSDTime != null) {
                        String playtime = Utils.OSD2Time(OSDTime);
                        if (!playtime.equals(mRecordTime)) {
                            mRecordSecond++;
                            mRecordTime = playtime;
                        }
                    }
                }*/
                sendMessage(RemoteListContant.MSG_REMOTELIST_UI_UPDATE, 0, 0);
            }
        };
        // 延时1000ms后执行，1000ms执行一次
        mUpdateTimer.schedule(mUpdateTimerTask, 0, 1000);
    }

    private void sendMessage(int message, int arg1, int arg2) {
        if (playBackHandler != null) {
            Message msg = playBackHandler.obtainMessage();
            msg.what = message;
            msg.arg1 = arg1;
            msg.arg2 = arg2;
            playBackHandler.sendMessage(msg);
        }
    }

    private void replay() {
        if (mPlaybackPlayer == null) return;
        mPlaybackPlayer.stopPlayback();
        // mPlaybackPlayer.stopLocalRecord();


        ivPause.setImageResource(R.mipmap.ic_gm_video_pause);
        notPause = false;

        slider.setCurrentProgress(0);

        mPlaybackPlayer.startPlayback(playbackFile.getStartTime(), playbackFile.getStopTime());
        status = RemoteListContant.STATUS_PLAYING;

    }

    private void newPlayInit() {
        isReplay = true;
        ivPause.setImageResource(R.mipmap.ic_gm_video_play);
        notPause = true;
        status = RemoteListContant.STATUS_STOP;
    }

    // 停止定时器
    private void stopUpdateTimer() {
        mControlDisplaySec = 0;
        // 停止录像计时
        if (mUpdateTimer != null) {
            mUpdateTimer.cancel();
            mUpdateTimer = null;
        }

        if (mUpdateTimerTask != null) {
            mUpdateTimerTask.cancel();
            mUpdateTimerTask = null;
        }
    }

    private boolean notPause = true;

    private void playOrPause() {


        if(isReplay){
            replay();
            isReplay = false;
            return;
        }

        if (notPause) {
            // 暂停播放
            notPause = false;
            ivPause.setImageResource(R.mipmap.ic_gm_video_play);
            // pauseBtn.setBackgroundResource(R.drawable.remote_list_play_btn_selector);
            if (status != RemoteListContant.STATUS_PLAYING) {
                pauseStop();
            } else {
                status = RemoteListContant.STATUS_PAUSE;
                if (mPlaybackPlayer != null) {
                    // 停止录像
                    //stopRemotePlayBackRecord();
                    // 加保护，规避CAS库小概率出现的10S死锁导致的ANR问题
                    getTaskManager().submit(new Runnable() {
                        @Override
                        public void run() {
                            mPlaybackPlayer.pausePlayback();
                        }
                    });
                }
            }
        } else {
            notPause = true;
            ivPause.setImageResource(R.mipmap.ic_gm_video_pause);
            //  pauseBtn.setBackgroundResource(R.drawable.ez_remote_list_pause_btn_selector);
            if (status != RemoteListContant.STATUS_PAUSE) {
                pausePlay();
            } else {
                if (mPlaybackPlayer != null) {
                    // 加保护，规避CAS库小概率出现的10S死锁导致的ANR问题
                    getTaskManager().submit(new Runnable() {
                        @Override
                        public void run() {
                            mPlaybackPlayer.resumePlayback();
                        }
                    });
                }
                status = RemoteListContant.STATUS_PLAYING;
            }
        }
    }

    private void pausePlay() {
        Calendar seekTime = getTimeBarSeekTime();
        Calendar osdTime = null;
        if (mPlaybackPlayer != null) {
            osdTime = mPlaybackPlayer.getOSDTime();
        }
        Calendar startTime = Calendar.getInstance();
        long playTime = 0L;
        if (osdTime != null) {
            playTime = osdTime.getTimeInMillis();
        } else {
            playTime = seekTime.getTimeInMillis();
        }
        startTime.setTimeInMillis(playTime);
        LogUtils.i("pausePlay:" + startTime);
      /*  if (currentClickItemFile != null) {
            reConnectPlay(currentClickItemFile.getType(), startTime);
        }*/

    }

    // 暂停按钮实现停止
    private void pauseStop() {
        status = RemoteListContant.STATUS_STOP;
        stopRemoteListPlayer();
    }

    private void closePlayBack() {
        if (status == RemoteListContant.STATUS_EXIT_PAGE) {
            return;
        }
        LogUtils.d("停止运行.........");
        stopPlayTask();
        stopRemoteListPlayer();

        onActivityStopUI();
        stopUpdateTimer();
        status = RemoteListContant.STATUS_EXIT_PAGE;
        if (surfaceView != null)
            surfaceView.setVisibility(View.GONE);
    }

    private void onActivityStopUI() {
        mControlDisplaySec = 0;
    }

    // 停止播放录像任务
    private void stopPlayTask() {
    }

    private void stopRemoteListPlayer() {
        try {
            if (mPlaybackPlayer != null) {
                mPlaybackPlayer.stopPlayback();
                mPlaybackPlayer.stopLocalRecord();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private Calendar getTimeBarSeekTime() {
        if (playbackFile != null) {
            long beginTime = playbackFile.getStartTime().getTimeInMillis();
            long endTime = playbackFile.getStopTime().getTimeInMillis();
            int progress = slider.getCurrentProgress();
            long seekTime = (((endTime - beginTime) * progress) / RemoteListContant.PROGRESS_MAX_VALUE) + beginTime;
            Calendar c = Calendar.getInstance();
            c.setTimeInMillis(seekTime);
            return c;
        }
        return null;
    }

    private MyHandler playBackHandler = new MyHandler(this);

    private static class MyHandler extends Handler {

        private WeakReference<GMOrderVideoPlayBackActivity> weakReference;

        public MyHandler(GMOrderVideoPlayBackActivity activity) {
            weakReference = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                // 片段播放完毕
                // 380061即开始时间>=结束时间，播放完成
                case ErrorCode.ERROR_CAS_RECORD_SEARCH_START_TIME_ERROR:
                    weakReference.get().handlePlaySegmentOver();
                    break;
                // 画面显示第一帧
                case EZConstants.EZPlaybackConstants.MSG_REMOTEPLAYBACK_PLAY_SUCCUSS:
                    weakReference.get().handleFirstFrame(msg);
                    break;
                case EZConstants.EZPlaybackConstants.MSG_REMOTEPLAYBACK_STOP_SUCCESS:
                    weakReference.get().handleStopPlayback();
                    break;
                case EZConstants.EZPlaybackConstants.MSG_REMOTEPLAYBACK_PLAY_FAIL:
                    ErrorInfo errorInfo = (ErrorInfo) msg.obj;
                    weakReference.get().handlePlayFail(errorInfo);
                    break;
                // 处理播放链接异常
                case RemoteListContant.MSG_REMOTELIST_CONNECTION_EXCEPTION:
                    if (msg.arg1 == ErrorCode.ERROR_CAS_RECORD_SEARCH_START_TIME_ERROR) {
                        weakReference.get().handlePlaySegmentOver();
                    }
                    break;
                case RemoteListContant.MSG_REMOTELIST_UI_UPDATE:
                    weakReference.get().updateRemotePlayUI();
                    break;
                case RemoteListContant.MSG_REMOTELIST_STREAM_TIMEOUT:
                    weakReference.get().handleStreamTimeOut();
                    break;
                default:
                    break;
            }
        }
    }


    private void handlePlaySegmentOver() {
        showMessage("播放结束");
        status = RemoteListContant.STATUS_STOP;
        newPlayInit();
    }

    private void handlePlayFail(ErrorInfo errorInfo) {
        status = RemoteListContant.STATUS_STOP;
        int errorCode = errorInfo.errorCode;

        switch (errorCode) {
            case ErrorCode.ERROR_TRANSF_ACCESSTOKEN_ERROR: {
            }
            // 收到这两个错误码，可以弹出对话框，让用户输入密码后，重新取流预览
            case ErrorCode.ERROR_INNER_VERIFYCODE_NEED:
            case ErrorCode.ERROR_INNER_VERIFYCODE_ERROR:
                showMessage("VERIFYCODE校验异常!");
                break;
            default: {
                String errorInfoText;
                if (errorCode == ErrorCode.ERROR_CAS_CONNECT_FAILED) {
                    errorInfoText = "连接服务器失败，请重试";
                } else if (errorCode == 2004/*VideoGoNetSDKException.VIDEOGONETSDK_DEVICE_EXCEPTION*/) {
                    errorInfoText = "播放失败，连接设备异常";
                } else if (errorCode == InnerException.INNER_DEVICE_NOT_EXIST) {
                    // 提示播放失败
                    errorInfoText = "设备不在线";
                } else {
                    errorInfoText = "视频播放失败";
                }
                showMessage(errorInfoText);
                // showPlayEventTip(errorInfoText);
                if (errorCode == ErrorCode.ERROR_CAS_STREAM_RECV_ERROR
                        || errorCode == ErrorCode.ERROR_TRANSF_DEVICE_OFFLINE
                        || errorCode == ErrorCode.ERROR_CAS_PLATFORM_CLIENT_REQUEST_NO_PU_FOUNDED
                        || errorCode == ErrorCode.ERROR_CAS_MSG_PU_NO_RESOURCE) {
                    // updateCameraInfo();
                }
            }
        }
    }

    private void handleFirstFrame(Message msg) {
        status = RemoteListContant.STATUS_PLAYING;
        containerLoading.setVisibility(View.GONE);
        if (isSoundEnable) {
            mPlaybackPlayer.openSound();
            isSoundEnable = true;
        }
    }

    private void handleStopPlayback() {
    }

    private void updateRemotePlayUI() {
        if (mPlaybackPlayer != null && status == RemoteListContant.STATUS_PLAYING) {
            Calendar osd = mPlaybackPlayer.getOSDTime();
            if (osd != null)
                handlePlayProgress(osd);
        }
    }

    private void handleStreamTimeOut() {
    }


    private void handlePlayProgress(Calendar osdTime) {
        long osd = osdTime.getTimeInMillis();
        long begin = playbackFile.getStartTime().getTimeInMillis();
        long end = playbackFile.getStopTime().getTimeInMillis();
        double x = ((osd - begin) * RemoteListContant.PROGRESS_MAX_VALUE) / (double) (end - begin);
        int progress = (int) x;
        slider.setCurrentProgress(progress);
        //progressBar.setProgress(progress);

        LogUtils.i("handlePlayProgress, begin time:" + begin + " endtime:" + end
                + " osdTime:" + osdTime.getTimeInMillis() + " progress:" + progress
        );

        int beginTimeClock = (int) ((osd - begin) / 1000);
        //updateTimeBucketBeginTime(beginTimeClock);
    }

    // 更新录像时间
    private void updateRecordTime() {
        // 计算分秒
        int leftSecond = mRecordSecond % 3600;
        int minitue = leftSecond / 60;
        int second = leftSecond % 60;

        // 显示录像时间
        String recordTime = String.format("%02d:%02d", minitue, second);
        tvCurrentTime.setText(recordTime);
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (notPause) {
            closePlayBack();
        }
    }

    protected void onDestroy() {
        super.onDestroy();
        closePlayBack();
        if (mPlaybackPlayer != null) {
            EZOpenSDK.getInstance().releasePlayer(mPlaybackPlayer);
        }

        removeHandler(playBackHandler);
    }

    protected void removeHandler(Handler handler) {
        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
        }
    }

    private static TaskManager mTaskManager = null;

    protected synchronized static TaskManager getTaskManager() {
        if (mTaskManager == null) {
            mTaskManager = new TaskManager();
        }
        return mTaskManager;
    }

    /**
     * download video from ezviz device
     *
     * @param deviceFile video file of device SdCard
     */
    private void startDownloadDeviceVideo(final EZDeviceRecordFile deviceFile) {
        if (deviceFile == null) {
            return;
        }
        final String notificationTitle = "download video from sdcard";
        final int notificationId = getUniqueNotificationId();
        showSimpleNotification(mContext, notificationId, notificationTitle, "downloading...click to cancel!", true);
        getTaskManager().submit(() -> {
            String strRecordFilePath = getExternalCacheDir() + "/Records/device_" + System.currentTimeMillis() + ".mp4";
            File file = new File(strRecordFilePath);
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }

            final EZDeviceStreamDownload ezDeviceStreamDownloader = new EZDeviceStreamDownload(strRecordFilePath, deviceInfo.getDeviceSerial(), deviceInfo.getCameraNo(), deviceFile);
            ezDeviceStreamDownloader.setStreamDownloadCallback(new EZStreamDownloadCallbackWithNotify(notificationId, notificationTitle));
            ezDeviceStreamDownloader.setSecretKey(deviceInfo.getVerifyCode());
            ezDeviceStreamDownloader.start();
            mDownloadTaskRecordListAbstract.add(new DownloadTaskRecordOfDevice(ezDeviceStreamDownloader, notificationId));

/*
            dialog(notificationTitle, "Note! It is very slow to download video from sdcard because of the device's limits! " +
                    "It will spend time about video length. So please wait patiently, and you can find download progress from notification bar.");
*/
        });
    }

    public static ArrayList<DownLoadTaskRecordAbstract> mDownloadTaskRecordListAbstract = new ArrayList<>();

    private static int mNotificationId = 1;

    protected static int getUniqueNotificationId() {
        return mNotificationId++;
    }

    /**
     * 展示下载通知
     *
     * @param context
     * @param notificationId
     * @param title
     * @param content
     * @param clickToCancel
     */
    public static void showSimpleNotification(Context context, int notificationId, String title, String content, boolean clickToCancel) {
        LogUtils.d("show notification " + notificationId);
        Intent intent = new Intent(MyApplication.getInstance(), NotificationReceiver.class)
                .putExtra(ReceiverKeys.NOTIFICATION_ID, notificationId);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context, ReceiverKeys.NOTIFICATION_ID)
                .setContentTitle(title)
                .setStyle(new NotificationCompat.BigTextStyle().bigText(content))
                .setWhen(System.currentTimeMillis())
                .setSmallIcon(R.mipmap.ic_logo)
                .setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_logo))
                .setPriority(NotificationCompat.PRIORITY_MAX);
        // 点击发送通知到NotificationReceiver
        if (clickToCancel) {
            notificationBuilder.setContentIntent(PendingIntent.getBroadcast(context, notificationId, intent, PendingIntent.FLAG_UPDATE_CURRENT));
        }
        NotificationManager notificationManager = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
        if (notificationManager != null) {
            notificationManager.notify(notificationId, notificationBuilder.build());
        }
    }

    private class EZStreamDownloadCallbackWithNotify extends EZOpenSDKListener.EZStreamDownloadCallbackEx {

        private int notificationId;
        private String notificationTitle;

        public EZStreamDownloadCallbackWithNotify(int notificationId, String notificationTitle) {
            this.notificationId = notificationId;
            this.notificationTitle = notificationTitle;
        }

        @Override
        public void onSuccess(final String filepath) {
            String successMsg = "saved video to " + filepath;
            LogUtils.d(successMsg);
            showMessage(successMsg);
            updateNotification(notificationId, successMsg);
        }

        @Override
        public void onError(final EZOpenSDKListener.EZStreamDownloadError code) {
            String failMsg = "failed: ";
            switch (code) {
                case ERROR_EZSTREAM_DOWNLOAD_MAX_CONNECTIONS:
                    failMsg += " device reached max connections!";
                    break;
                default:
                    failMsg += code;
                    break;
            }
            LogUtils.d(failMsg);
            updateNotification(notificationId, failMsg);
        }

        @Override
        public void onErrorCode(int code) {
            showMessage("onErrorCode: " + code);
        }

        private void updateNotification(int id, String content) {
            showSimpleNotification(mContext, id, notificationTitle, content, false);
        }
    }

    public static class NotificationReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            int notificationId = intent.getIntExtra(ReceiverKeys.NOTIFICATION_ID, -1);
            LogUtils.d("onClick, notificationId is " + notificationId);
            DownLoadTaskRecordAbstract downLoadTaskRecord = null;
            for (DownLoadTaskRecordAbstract downLoadTaskRecordAbstract : mDownloadTaskRecordListAbstract) {
                if (downLoadTaskRecordAbstract.getNotificationId() == notificationId) {
                    LogUtils.d("stopped download task which related to notificationId " + notificationId);
                    downLoadTaskRecord = downLoadTaskRecordAbstract;
                    downLoadTaskRecord.stopDownloader();
                }
            }
            if (downLoadTaskRecord != null) {
                mDownloadTaskRecordListAbstract.remove(downLoadTaskRecord);
            }
            NotificationManager notificationManager = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
            if (notificationManager != null) {
                notificationManager.cancel(notificationId);
                UToast.showShort(context, "canceled to downloaded!");
            }
        }
    }

    private static void stopAllDownloadTasks() {
        for (DownLoadTaskRecordAbstract downloadRecord : mDownloadTaskRecordListAbstract) {
            downloadRecord.stopDownloader();
        }
    }
}
